/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025-02-15
 */
public class Leetcode_24 {
    public static void main(String[] args) {
        // 创建链表并测试
        Leetcode_24 solution = new Leetcode_24();

        // 构造测试链表 [1 -> 2 -> 3 -> 4]
        ListNode head = solution.createList(new int[]{1, 2, 3, 4});

        // 调用 swapPairs 方法交换节点
        ListNode result = solution.swapPairs(head);

        // 打印交换后的链表
        solution.printList(result);  // 输出: 2 -> 1 -> 4 -> 3
    }

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode headNode = new ListNode(0, head);  // 虚拟头节点
        ListNode cur = headNode;
        while (cur != null && cur.next != null && cur.next.next != null) {
            // 交换当前节点和下一个节点
            ListNode tmp = cur.next.next;
            cur.next.next = tmp.next;
            tmp.next = cur.next;
            cur.next = tmp;
            cur = cur.next.next;  // 移动到下一个待交换的节点
        }
        return headNode.next;  // 返回新的头节点（跳过虚拟头节点）
    }

    // 辅助方法：打印链表
    public void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val);
            if (current.next != null) {
                System.out.print(" -> ");
            }
            current = current.next;
        }
        System.out.println();
    }

    // 辅助方法：根据数组创建链表
    public ListNode createList(int[] arr) {
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    // ListNode 定义
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {}

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
